import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import api from '@/utils/api'

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const token = ref(localStorage.getItem('token') || '')
  const user = ref(JSON.parse(localStorage.getItem('user') || 'null'))
  const loading = ref(false)

  // 计算属性
  const isAuthenticated = computed(() => !!token.value)
  const userRole = computed(() => user.value?.role || '')
  const userName = computed(() => user.value?.name || '')
  const isAdmin = computed(() => userRole.value === 'admin')
  const isTeacher = computed(() => userRole.value === 'teacher')
  const isDriver = computed(() => userRole.value === 'driver')
  const isAfterSchoolTeacher = computed(() => userRole.value === 'after_school_teacher')

  // 设置认证信息
  const setAuth = (authToken, userData) => {
    token.value = authToken
    user.value = userData
    localStorage.setItem('token', authToken)
    localStorage.setItem('user', JSON.stringify(userData))
    api.defaults.headers.common['Authorization'] = `Bearer ${authToken}`
  }

  // 清除认证信息
  const clearAuth = () => {
    token.value = ''
    user.value = null
    localStorage.removeItem('token')
    localStorage.removeItem('user')
    delete api.defaults.headers.common['Authorization']
  }

  // 登录
  const login = async (credentials) => {
    loading.value = true
    try {
      const response = await api.post('/auth/login', credentials)
      const { token: authToken, user: userData } = response.data.data
      
      setAuth(authToken, userData)
      return { success: true, data: userData }
    } catch (error) {
      const message = error.response?.data?.message || '登录失败'
      return { success: false, message }
    } finally {
      loading.value = false
    }
  }

  // 登出
  const logout = () => {
    clearAuth()
  }

  // 获取用户信息
  const fetchProfile = async () => {
    try {
      const response = await api.get('/auth/profile')
      user.value = { ...user.value, ...response.data.data }
      localStorage.setItem('user', JSON.stringify(user.value))
      return { success: true, data: user.value }
    } catch (error) {
      const message = error.response?.data?.message || '获取用户信息失败'
      return { success: false, message }
    }
  }

  // 修改密码
  const changePassword = async (passwords) => {
    loading.value = true
    try {
      await api.put('/auth/change-password', passwords)
      return { success: true, message: '密码修改成功' }
    } catch (error) {
      const message = error.response?.data?.message || '修改密码失败'
      return { success: false, message }
    } finally {
      loading.value = false
    }
  }

  // 验证令牌
  const verifyToken = async () => {
    if (!token.value) return false
    
    try {
      const response = await api.post('/auth/verify-token')
      const userData = response.data.data
      user.value = userData
      localStorage.setItem('user', JSON.stringify(userData))
      return true
    } catch (error) {
      clearAuth()
      return false
    }
  }

  // 初始化（设置axios header）
  const init = () => {
    if (token.value) {
      api.defaults.headers.common['Authorization'] = `Bearer ${token.value}`
    }
  }

  return {
    // 状态
    token,
    user,
    loading,
    
    // 计算属性
    isAuthenticated,
    userRole,
    userName,
    isAdmin,
    isTeacher,
    isDriver,
    isAfterSchoolTeacher,
    
    // 方法
    login,
    logout,
    fetchProfile,
    changePassword,
    verifyToken,
    init,
    setAuth,
    clearAuth
  }
})
